/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tos.semaphore;

import java.util.concurrent.Semaphore;
import org.jdesktop.application.FrameView;
import tos.TosView;

/**
 *
 * @author Milos
 */
public class Smanjivac extends Thread {

    private String ime;
    private Semaphore semafor;
    private int brojSmanjenja;
    private Brojac brojac;
    private FrameView parent;

    public Smanjivac(String ime, Semaphore semafor, int brojPovecanja, Brojac brojac, FrameView parent) {
        this.ime = ime;
        this.semafor = semafor;
        this.brojSmanjenja = brojPovecanja;
        this.brojac = brojac;
        this.parent = parent;
    }

    public String getIme() {
        return ime;
    }

    public void setIme(String ime) {
        this.ime = ime;
    }

    public Semaphore getSemafor() {
        return semafor;
    }

    public int getBrojPovecanja() {
        return brojSmanjenja;
    }

    public void setBrojPovecanja(int brojPovecanja) {
        this.brojSmanjenja = brojPovecanja;
    }

    public void setSemafor(Semaphore semafor) {
        this.semafor = semafor;
    }

    public Brojac getBrojac() {
        return brojac;
    }

    public void setBrojac(Brojac brojac) {
        this.brojac = brojac;
    }

    private void smanjiBrojac() {
        System.out.println(ime + " ceka na dozvolu.");
        ((TosView) parent).appendOutput(ime + " ceka na dozvolu.\n");
        try {
            semafor.acquire();
        } catch (InterruptedException ex) {
            System.out.println("Greska " + ex);
        }
        System.out.println(ime + " je dobio dozvolu.");
        ((TosView) parent).appendOutput(ime + " je dobio dozvolu.\n");
        int temp = brojac.getBrojac();
        temp--;
        brojac.setBrojac(temp);
        System.out.println(ime + " je oslobodio dozvolu.");
        ((TosView) parent).appendOutput(ime + " je oslobodio dozvolu.\n");
        semafor.release();
    }

    @Override
    public void run() {
        System.out.println(ime + " krenuo!");
        ((TosView) parent).appendOutput(ime + " krenuo!\n");
        try {
            for (int i = 0; i < brojSmanjenja; i++) {
                smanjiBrojac();
                sleep(25);
            }
        } catch (InterruptedException ex) {
            System.out.println("Greska " + ex);
        }

    }
}
